package com.wangyg.sort;

import com.google.common.base.Joiner;

/**
 * Created by wangyg6 on 2019/7/1 15:46.
 * 冒泡和插入很像,冒泡是每次交换两个，而插入是每次比较但是不换，最后换
 */
public class bubble {
	public static Integer[] rawdata = new Integer[] { 3, 7, 1, 55, 32, 69, 38, 14, 6, 5, 2, 7 };
	private static Joiner joiner = Joiner.on(" <= ").skipNulls();

	public static void main(String[] args) {
		//		Integer[] ints = bubbleSort(rawdata);
		//		Integer[] ints = selectionSort(rawdata);
		Integer[] ints = insertionSort(rawdata);

		System.out.println(joiner.join(ints));
	}

	/**
	 * 冒泡排序
	 * @param param
	 * @return
	 */
	public static Integer[] bubbleSort(Integer[] param) {
		if (param == null || param.length == 0) {
			throw new IllegalArgumentException("入参不可为空");
		}
		int x = param.length;//数组长度
		for (int i = 0; i < x - 1; i++) {
			for (int j = 0; j < x - i - 1; j++) {
				if (param[j] > param[j + 1]) {
					int temp = param[j + 1];
					param[j + 1] = param[j];
					param[j] = temp;
					//					System.out.println("i = " + i + ",j = " + j);
				}
				System.out.println("i = " + i + ",j = " + j);
			}
		}

		return param;
	}

	//public static Integer[] rawdata = new Integer[] { 3, 7, 1, 55, 32, 69, 38, 14, 6, 5, 2, 7 };
	public static Integer[] selectionSort(Integer[] param) {
		if (param == null || param.length == 0) {
			throw new IllegalArgumentException("入参不可为空");
		}
		System.out.println(joiner.join(param));
		int x = param.length;//数组长度//12
		for (int i = 0; i < x - 1; i++) {//0-11
			int y = 0;//最大值的下标
			for (int j = 0; j < x - i; j++) {
				if (param[y] <= param[j]) {
					y = j;
					System.out.println("i=" + i + ",j=" + j + ",y=" + y);
				}
			}
			System.out.println(y);
			Integer temp = param[x - i - 1];
			param[x - i - 1] = param[y];
			param[y] = temp;
			System.out.println(x - i - 1);
			System.out.println(joiner.join(param));
		}

		return param;
	}
	//public static Integer[] rawdata = new Integer[] { 3, 7, 1, 55, 32, 69, 38, 14, 6, 5, 2, 7 };
	public static Integer[] insertionSort(Integer[] param) {
		if (param == null || param.length == 0) {
			throw new IllegalArgumentException("入参不可为空");
		}
		int x = param.length;//数组长度//12
		for (int i = 0; i < x - 1; i++) {//0-11
			for (int j = i + 1; j > 0; j--) {
				if (param[j] < param[j - 1]) {
					int temp = param[j];
					param[j] = param[j - 1];
					param[j - 1] = temp;
					System.out.println(joiner.join(param));
				}
			}
		}
		return param;
	}
}
